package com.chenglu.android.store;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chenglu.android.R;
import com.chenglu.android.common.base.BaseFullScreenActivity;
import com.chenglu.android.common.base.Global;
import com.chenglu.android.common.net.Constant;
import com.chenglu.android.common.utils.GlideUtils;
import com.chenglu.android.common.utils.LogUtils;
import com.chenglu.android.common.utils.StatusBarUtil;
import com.chenglu.android.common.utils.ToastUtils;
import com.chenglu.android.goodsinfo.bean.ShopsinfoBean;
import com.chenglu.android.goodsinfo.infoutils.GoodsInfoUtils;
import com.chenglu.android.index.bean.IndexRecomBean;
import com.chenglu.android.search.SearchHistoryActivity;
import com.chenglu.android.store.adapter.BangAdapter;
import com.chenglu.android.store.adapter.RecommendGoodsAdapter;
import com.chenglu.android.store.adapter.SearchGoodsAdapter;
import com.chenglu.android.store.bean.ChartBangBean;
import com.chenglu.android.store.mvp.contract.StoreContract;
import com.chenglu.android.store.mvp.presenter.StorePresenter;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author: lyj
 * @Created: by Copyright 2023/10/24 Guangzhou Hongma Technology Co., Ltd. All rights reserved.
 * @Description： 商超的类似的店铺页 目前不用
 */
public class StoreActivity extends BaseFullScreenActivity<StorePresenter> implements StoreContract.View {

    public static final String TENANTID = "tenantId";
    @BindView(R.id.ic_back)
    ImageView icBack;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_recommend)
    TextView tvRecommend;
    @BindView(R.id.tv_goods)
    TextView tvGoods;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.iv_shop_header)
    ImageView ivShopHeader;
    @BindView(R.id.cv_user)
    CardView cvUser;
    @BindView(R.id.tv_shopname)
    TextView tvShopname;
    @BindView(R.id.ratingBar_service)
    RatingBar ratingBarService;
    @BindView(R.id.rt_shop_des)
    RelativeLayout rtShopDes;
    @BindView(R.id.rv_bang_store)
    RecyclerView rvBangStore;
    @BindView(R.id.rv_shop_recommend)
    RecyclerView rvShopRecommend;
    @BindView(R.id.tv_ruby_synthesize)
    TextView tvRubySynthesize;
    @BindView(R.id.tv_sell_number)
    TextView tvSellNumber;
    @BindView(R.id.rt_ruby_sell)
    RelativeLayout rtRubySell;
    @BindView(R.id.tv_ruby_price)
    TextView tvRubyPrice;
    @BindView(R.id.iv_ruby_price)
    ImageView ivRubyPrice;
    @BindView(R.id.rt_ruby_price)
    RelativeLayout rtRubyPrice;
    @BindView(R.id.rv_search_product)
    RecyclerView rvSearchProduct;
    @BindView(R.id.smartrefreshlayout)
    SmartRefreshLayout smartrefreshlayout;
    @BindView(R.id.ll_loading_data)
    LinearLayout llLoadingData;
    @BindView(R.id.tv_sales_chart)
    TextView tvSalesChart;
    @BindView(R.id.tv_collect_chart)
    TextView tvCollectChart;
    @BindView(R.id.tv_new_chart)
    TextView tvNewChart;
    @BindView(R.id.ll_recommend)
    LinearLayout llRecommend;
    @BindView(R.id.ll_goods)
    LinearLayout llGoods;
    @BindView(R.id.ll_loading_no_data)
    LinearLayout llLoadingNoData;
    @BindView(R.id.rl_bang)
    RelativeLayout rlBang;
    @BindView(R.id.tv_no_bang_data)
    TextView tvNoBangData;
    @BindView(R.id.ll_bang_bg)
    LinearLayout llBangBg;

    private BangAdapter bangAdapter;
    private SearchGoodsAdapter searchGoodsAdapter;
    private RecommendGoodsAdapter recommendGoodsAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store);
        ButterKnife.bind(this);
        StatusBarUtil.immersive(this, R.color.white);
        StatusBarUtil.setPaddingSmart(this, toolbar);

        tenantId = getIntent().getStringExtra(TENANTID);
        mPresenter = new StorePresenter();
        mPresenter.attachView(this);

        ImmersionBar.with(this)
                .statusBarColor(R.color.white)
                .statusBarDarkFont(true)
                .fullScreen(true)
                .init();


        //榜单切换
        initBangAdapter();


        initRecommendGoodsAdapter();

        initSearchGoodsAdapter();


        initData();

    }

    private String tenantId;
    private int bangStatus = 1;
    private int current = 1;

    private String shopsTypeId = "1";

    //请求数据
    private void initData() {
        initRefreshLayout();

        mPresenter.getShopinfo(tenantId);
//         mPresenter.getShopsTypes();

        mPresenter.getShopsTypes(getToken(), bangStatus, tenantId);

        mPresenter.getLikeLists(setRecommentParam());


        setSearchGoodsParam(current, "", "", shopsTypeId);

    }

    private Map<String, String> setRecommentParam() {

        Map<String, String> productMap = new HashMap<>();

        productMap.put("yourLike", Constant.one);
        productMap.put("size", Constant.SIZE + "");
//        productMap.put("tentanId", tenantId);

        return productMap;
    }

    private void setSearchGoodsParam(int current, String priceSort, String salesAmountSort, String shopsTypeId) {

        Map<String, String> productMap = new HashMap<>();


//        productMap.put("categoryId",categoryId);
        productMap.put("current", current + "");
        productMap.put("size", 8 + "");   //

        if (!TextUtils.isEmpty(priceSort)) {
            productMap.put("goodsPriceSort", priceSort); //根据商品价格排序(desc,asc)
        }
        if (!TextUtils.isEmpty(salesAmountSort)) {
            productMap.put("salesAmountSort", ""); //根据销量排序(desc,asc)
        }

//        if(!TextUtils.isEmpty(newSort)){
//            productMap.put("createTimeSort", priceSort); //根据新品排序(desc,asc)
//        }

        if (!TextUtils.isEmpty(shopsTypeId)) {
            productMap.put("shopsTypeId", shopsTypeId); //shopsTypeId 模块搜索
        }
        productMap.put("tenantId", tenantId);

        mPresenter.getSearchGoods(productMap);
    }

    List<ChartBangBean.Data> bangBeanList = new ArrayList<>();

    private void initBangAdapter() {
        //排序有问题
//        bangAdapter = new BangAdapter(mContext, bangBeanList);
//
//        rvBangStore.setLayoutManager(new LinearLayoutManager(this));
//
//        rvBangStore.setAdapter(bangAdapter);
//        searchAdapter.notifyDataSetChanged();


    }

    List<IndexRecomBean.Data.Records> goodsSearchList = new ArrayList<>();


    private void initSearchGoodsAdapter() {

        //排序有问题
        searchGoodsAdapter = new SearchGoodsAdapter(mContext, goodsSearchList);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 2);
        rvSearchProduct.setLayoutManager(gridLayoutManager);

        rvSearchProduct.setAdapter(searchGoodsAdapter);
//        searchGoodsAdapter.notifyDataSetChanged();

        searchGoodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                GoodsInfoUtils.goodsInfo(mContext, searchGoodsAdapter.getData().get(position).getId(),Integer.parseInt(shopsTypeId));
//
            }
        });
    }

    List<IndexRecomBean.Data.Records> recommendList = new ArrayList<>();

    private void initRecommendGoodsAdapter() {

        //排序有问题
        recommendGoodsAdapter = new RecommendGoodsAdapter(mContext, recommendList);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 2);
        rvShopRecommend.setLayoutManager(gridLayoutManager);

        rvShopRecommend.setAdapter(recommendGoodsAdapter);
//        searchAdapter.notifyDataSetChanged();

        recommendGoodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                GoodsInfoUtils.goodsInfo(mContext, recommendGoodsAdapter.getData().get(position).getId(),Integer.parseInt(shopsTypeId));
//
            }
        });
    }

    private int state;
    private String priceSort;
    private String salesAmountSort;
    private boolean isPriceSort = true; // true=1 false =2

    //刷新
    private void initRefreshLayout() {

        smartrefreshlayout.setEnableRefresh(false);

        smartrefreshlayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //id 需要传参过来
                current = 1;
                //需要清空数据再加
                recommendList.clear();
                switch (state) {
                    case 0:
                        setSearchGoodsParam(current, "", "", shopsTypeId);
                        break;
                    case 1:
                        setSearchGoodsParam(current, "", salesAmountSort, shopsTypeId);
                        break;
                    case 2:
                        setSearchGoodsParam(current, priceSort, "", shopsTypeId);

                }


            }
        });
        smartrefreshlayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                current += 1;
                LogUtils.v("ruby--", current + "");
                switch (state) {
                    case 0:
                        setSearchGoodsParam(current, "", "", shopsTypeId);
                        break;
                    case 1:
                        setSearchGoodsParam(current, "", salesAmountSort, shopsTypeId);
                        break;
                    case 2:
                        setSearchGoodsParam(current, priceSort, "", shopsTypeId);

                }
//                setSearchData(categoryId, currentSearchName, current, Constant.SIZE);

            }
        });
    }

    @OnClick({R.id.ll_back, R.id.tv_recommend, R.id.tv_goods, R.id.tv_sales_chart, R.id.tv_collect_chart, R.id.tv_new_chart, R.id.tv_ruby_synthesize, R.id.rt_ruby_sell, R.id.rt_ruby_price
    ,R.id.icon_search,R.id.rt_shop_des})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rt_shop_des:
                startActivity(new Intent(this, StoreInfoActivity.class)
                .putExtra("tenandId",tenantId));
                break;
            case R.id.icon_search:
                startActivity(new Intent(this, SearchHistoryActivity.class));
                break;
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_recommend:
                //切换页面
                setTitleChange(R.color.color_f7f7f7, R.color.all_black_text, 5, 6, View.VISIBLE, View.GONE);
                break;
            case R.id.tv_goods:

                setTitleChange(R.color.all_black_text, R.color.color_f7f7f7, 6, 5, View.GONE, View.VISIBLE);
                break;
            case R.id.tv_sales_chart:
                llBangBg.setBackground(mContext.getResources().getDrawable(R.drawable.corners_store_shape_8));
                bangBeanList.clear();
                mPresenter.getShopsTypes(getToken(), 1, tenantId);

                setBangChange(R.drawable.corners_tv_store1_shape_8, R.color.white, R.drawable.corners_f6f6f6_default, R.color.home_new_color, R.drawable.corners_f6f6f6_default, R.color.home_new_color);
                break;
            case R.id.tv_collect_chart:
                llBangBg.setBackground(mContext.getResources().getDrawable(R.drawable.corners_store_shape_8));
                bangBeanList.clear();
                mPresenter.getShopsTypes(getToken(), 2, tenantId);
                setBangChange(R.drawable.corners_f6f6f6_default, R.color.home_new_color, R.drawable.corners_tv_store2_shape_8, R.color.white, R.drawable.corners_f6f6f6_default, R.color.home_new_color);
                break;
            case R.id.tv_new_chart:
                llBangBg.setBackground(mContext.getResources().getDrawable(R.drawable.corners_store_shape_8));
                bangBeanList.clear();
                mPresenter.getShopsTypes(getToken(), 3, tenantId);
                setBangChange(R.drawable.corners_f6f6f6_default, R.color.home_new_color, R.drawable.corners_f6f6f6_default, R.color.home_new_color, R.drawable.corners_tv_store3_shape_8, R.color.white);
                break;
            case R.id.tv_ruby_synthesize:

                goodsSearchList.clear();
                current = 1;
                state = 0;
                setSearchGoodsParam(current, "", "", shopsTypeId);
                //请求数据
                setTextAndColor(R.color.home_new_color, R.color.black, R.color.black, R.drawable.icon_ruby_default);
                break;
            case R.id.rt_ruby_sell:
                goodsSearchList.clear();
                current = 1;
                state = 0;
                salesAmountSort = "asc";
                setSearchGoodsParam(current, "", salesAmountSort, shopsTypeId);
                //请求数据
                setTextAndColor(R.color.black, R.color.home_new_color, R.color.black, R.drawable.icon_ruby_default);
                break;
            case R.id.rt_ruby_price:

                goodsSearchList.clear();
                current = 1;
                state = 2;
                if (isPriceSort) {
                    priceSort = "asc";
                    setSearchGoodsParam(current, priceSort, "", shopsTypeId);
                    setTextAndColor(R.color.black, R.color.black, R.color.home_new_color, R.drawable.icon_ruby_up);
                    isPriceSort = false;
                } else {
                    priceSort = "desc";
                    setSearchGoodsParam(current, priceSort, "", shopsTypeId);
                    setTextAndColor(R.color.black, R.color.black, R.color.home_new_color, R.drawable.icon_ruby_down);
                    isPriceSort = true;
                }
                break;

        }
    }

    private void setBangChange(int p, int p2, int p3, int p4, int p5, int p6) {
        tvSalesChart.setBackground(mContext.getResources().getDrawable(p));
        tvSalesChart.setTextColor(mContext.getResources().getColor(p2));
        tvCollectChart.setBackground(mContext.getResources().getDrawable(p3));
        tvCollectChart.setTextColor(mContext.getResources().getColor(p4));
        tvNewChart.setBackground(mContext.getResources().getDrawable(p5));
        tvNewChart.setTextColor(mContext.getResources().getColor(p6));
    }


    //设置标题改变
    private void setTitleChange(int p, int p2, int i, int i2, int gone, int visible) {
        tvGoods.setTextColor(getResources().getColor(p));
        tvRecommend.setTextColor(getResources().getColor(p2));
        tvGoods.setTextSize(Global.dp2px(i));
        tvRecommend.setTextSize(Global.dp2px(i2));
        llRecommend.setVisibility(gone);
        llGoods.setVisibility(visible);
    }

    @Override
    public void getShopinfo(ShopsinfoBean bean) {

        tvShopname.setText(bean.getData().getShopsName());
        ratingBarService.setRating(bean.getData().getScore());
//        ratingBarService.setNumStars(bean.getData().getScore());
        GlideUtils.setImageView(mContext, bean.getData().getLogoImage(), ivShopHeader);
    }

    @Override
    public void onError(String errorMsg) {
        super.onError(errorMsg);
        ToastUtils.show(errorMsg);
        rlBang.setVisibility(View.GONE);
        tvNoBangData.setVisibility(View.VISIBLE);

    }

    @Override
    public void getShopsTypes(ChartBangBean bean) {

        if (bean.getData().size() > 0) {
            rlBang.setVisibility(View.VISIBLE);
            tvNoBangData.setVisibility(View.GONE);
            for (int i = 0; i < bean.getData().size(); i++) {
                bangBeanList.add(bean.getData().get(i));
            }
            bangAdapter.notifyDataSetChanged();
        } else {
            rlBang.setVisibility(View.GONE);
            tvNoBangData.setVisibility(View.VISIBLE);
        }


    }

    @Override
    public void getLikeLists(IndexRecomBean bean) {

        for (int i = 0; i < bean.getData().getRecords().size(); i++) {
            recommendList.add(bean.getData().getRecords().get(i));
        }
        recommendGoodsAdapter.notifyDataSetChanged();

    }

    boolean isAddFooterView = true;

    @Override
    public void getSearchGoods(IndexRecomBean bean) {

        stopRefresh(smartrefreshlayout);

        if (bean.getData().getRecords().size() > 0) {
            llLoadingData.setVisibility(View.VISIBLE);
            llLoadingNoData.setVisibility(View.GONE);
            for (int i = 0; i < bean.getData().getRecords().size(); i++) {
                //添加集合中banner的数据
                goodsSearchList.add(bean.getData().getRecords().get(i));
            }

            if (current * 8 > bean.getData().getTotal()) {
                smartrefreshlayout.setEnableLoadMore(false);

                if (isAddFooterView) {
                    View inflate = Global.inflate(R.layout.loadmore_addfooter_layout);
                    inflate.findViewById(R.id.tv_no_more).setBackgroundColor(getResources().getColor(R.color.color_f6f6f6));
                    searchGoodsAdapter.addFooterView(inflate);
                    isAddFooterView = false;
                }

            } else {
                isAddFooterView = true;
                searchGoodsAdapter.removeAllFooterView();
                smartrefreshlayout.setEnableLoadMore(true);

            }
            searchGoodsAdapter.notifyDataSetChanged();
        } else {
            if (goodsSearchList.isEmpty()) {
//                showEmptyView("暂无数据");
                llLoadingData.setVisibility(View.GONE);
                llLoadingNoData.setVisibility(View.VISIBLE);
            }

        }
    }

    @Override
    public void getShopsRecommendPage(IndexRecomBean bean) {

    }


    //设置不通的颜色和背景
    private void setTextAndColor(int p, int p2, int p3, int p5) {
        tvRubySynthesize.setTextColor(getResources().getColor(p));
        tvSellNumber.setTextColor(getResources().getColor(p2));
        tvRubyPrice.setTextColor(getResources().getColor(p3));
        //价格和红豆
        ivRubyPrice.setBackground(getResources().getDrawable(p5));

    }
}
